package com.candy.control;

import com.candy.service.LoginService;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
//    初始化的时候会被调用的
    @Override
    public void init(ServletConfig config) throws ServletException {
        System.out.println("servlet初始化处理...");
//       获取配置的initparam所对应的value属性
        String initparam=config.getInitParameter("init");
        System.out.println("获取初始化参数：initparam:"+initparam);
//        获取servlet名字
        System.out.println("servletname:"+config.getServletName());
//        获取ServletContext对象
        ServletContext context=config.getServletContext();
//        获取ServletContext初始化参数
        String contextValue=context.getInitParameter("contextname");
        System.out.println("获取ServletContext初始化参数：contextValue:"+contextValue);
    }

    //    处理get请求
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("以接收到客户端发送过来的请求");
//        处理字符集乱码问题
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
//        接收客户端传递进来的参数
//        getParameter获取表单中对应的name属性的value值
        String username=req.getParameter("username");
        String userpwd=req.getParameter("userpwd");
//        调用业务逻辑处理层
        LoginService service=new LoginService();
        boolean ok=service.login(username,userpwd);
//        如果用户名密码匹配，则跳转到登录成功的页面
        if(ok){
//            转发
            req.getRequestDispatcher("welcome.html").forward(req,resp);
        }else {
//            反之跳回到登录页面
//            重定向
            resp.sendRedirect("login.jsp");

        }
    }
//处理post请求
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
